package com.yc;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.model.output.Response;

import java.util.List;

public class RAG_App_1 {
    public static void main(String[] args) {
        //1。文本向量化
        QwenEmbeddingModel qwenEmbeddingModel =QwenEmbeddingModel.builder()
                .apiKey(System.getenv("AlI_API_KEY"))
                .build();
//文本向量化
        Response<Embedding> embed=qwenEmbeddingModel.embed("这是一只漂亮的小狗");
        System.out.println(embed.content().toString());//向量值
        System.out.println(embed.content().vector().length);//向量长度推度
//1,相以度比较
        Embedding emb1=qwenEmbeddingModel.embed("这是一只小狗").content();
        Embedding emb2=qwenEmbeddingModel.embed("那是一条g狗").content();
        Embedding emb3=qwenEmbeddingModel.embed("今天天气真w好").content();
        double sim =cosineSimilarity(emb3.vectorAsList(),embed.content().vectorAsList());
        System.out.println("相似度："+sim);//0.8976776706934477
//        0.79158395318063710.5304280499606998
//        sim cosineSimilarity(emb1.vectorAsList(),emb3.vectorAsList());
//        System.out.println("相似/度："+sim):
    }
    public static double cosineSimilarity(List<Float> a, List<Float>b){
        if (a.size()!=b.size()){
            throw new IllegalArgumentException("向量维度不一致");
        }
        double dotProduct =0.0;
        double normA =0.0;
        double normB =0.0;
        for (int i=0;i <a.size();i++){
            double x =a.get(i);
            double y =b.get(i);
            dotProduct +=x*y;
            normA +=x*x;
            normB +=y*y;
        }
            if (normA ==0.0 || normB ==0.0)return 0.0;
            return dotProduct /(Math.sqrt(normA)*Math.sqrt(normB));
}
        }